package zing.downloader.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileUtils {

    public static boolean isExistedFile(String fileName) {
        Pattern pattern = Pattern.compile("[^\\.+]\\(\\d\\)\\.mp3");
        Matcher matcher = pattern.matcher(fileName);
        return matcher.find();
    }

    public static String parseInputStream(InputStream is) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return sb.toString();

    }

    public static String getFileExtension(String fileName) {
        int index = fileName.lastIndexOf('.');
        return index > 0 ? fileName.substring(index + 1) : "";
    }

    public void deleteDuplicatedFile(String directory) {
        File dir = new File(directory);
        File[] directoryListing = dir.listFiles();
        if (directoryListing == null) {
            return;
        }
        for (File child : directoryListing) {
            if (FileUtils.isExistedFile(child.getName())) {
                child.delete();
            }
        }
    }

    public static String getSongNameFromRedirectedUrl(String redirectedUrl) {
        redirectedUrl = HtmlUtil.decodeUrlString(redirectedUrl);
        return HtmlUtil.getQueryString(redirectedUrl, "filename");
    }

    public static String createDirectoryIfNotExisted(String parentDir, String childDir) {
        try {
            File directory = new File(parentDir, childDir);

            if (!directory.exists()) {
                directory.mkdir();
            }
            return directory.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
